package scrapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.HttpStatusException;
import org.jsoup.nodes.Document;

public class SauceNaoScrapper extends AbstractScrapper {

	public SauceNaoScrapper(String id, String agent) {
		super(id, agent);
	}

	@Override
	public void login(String username, String password) throws IOException {}

	@Override
	public String buildURL(String id) { return null; }

	@Override
	public boolean buildPage() {
		Document page = getPage();
		
		if(page.select("div[class=resultsimilarityinfo]").size() > 0) {
			String rawSimilarity = getPage().select("div[class=resultsimilarityinfo]").get(0).text();
			int similarity = Integer.valueOf(rawSimilarity.substring(0, 2));
			String rawTitle = getPage().select("div[class=resulttitle]").get(0).text();
			
			/*<div class="resultcontentcolumn">
				<strong>Pixiv ID: </strong>
				<a href="http://www.pixiv.net/member_illust.php?mode=medium&amp;illust_id=41764898" class="linkify" target="_blank">41764898</a>
				<span style="padding-left:10px;">
					<a href="http://saucenao.com/info.php?lookup_type=0&amp;db=5&amp;id=41764898">
					<img src="/images/static/saucenao_info.png" height="10px" width="10px"></a>
				</span>
				<br>
				<strong>Member: </strong>
				<a href="http://www.pixiv.net/member.php?id=648285" class="linkify" target="_blank">mocha@み31ｂ</a>
				<span style="padding-left:10px;">
					<a href="http://saucenao.com/info.php?lookup_type=1&amp;db=5&amp;id=648285">
					<img src="/images/static/saucenao_info.png" height="10px" width="10px"></a>
				</span>
				<br>
			</div>*/
			
			if(page.select("div[class=resultcontentcolumn]").select("a").size() > 2) {
				String id = page.select("div[class=resultcontentcolumn]").select("a").get(0).text();
				String author = page.select("div[class=resultcontentcolumn]").select("a").get(2).text();
				String rawAuthor = page.select("div[class=resultcontentcolumn]").select("a").get(2).attr("href");
				rawAuthor = rawAuthor.replace("http:\\www.pixiv.net\\member.php?id=", "");
				if(rawAuthor.split("(id=)").length > 1)
					rawAuthor = rawAuthor.split("(id=)")[1];
				
				if(similarity > 85) {
					setTitle(rawTitle);
					setFile(id);
					setAuthor(author);
					setAuthorID(rawAuthor);
					
					System.out.println(toString());
					return true;
				}
				else
					return false;
			}
		}
		System.out.println("Problem encountered with the parser!");
		return false;
	}

	/*@SuppressWarnings("deprecation")
	public void uploadImage(File file) throws ClientProtocolException, IOException {
		String url = "http://saucenao.com/";
		String viewStateName = "javax.faces.ViewState";
		String submitButtonValue = "get sauce"; // Value of upload submit button.

		HttpClient httpClient = new DefaultHttpClient();
		HttpContext httpContext = new BasicHttpContext();
		httpContext.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore());

		HttpGet httpGet = new HttpGet(url);
		HttpResponse getResponse = httpClient.execute(httpGet, httpContext);
		Document document = Jsoup.parse(EntityUtils.toString(getResponse.getEntity()));

		//String viewStateValue = document.select("input[type=hidden][name=" + viewStateName + "]").val();
		String uploadFieldName = document.select("input[type=file]").attr("name");
		String submitButtonName = document.select("input[type=submit][value=" + submitButtonValue + "]").attr("name");

		System.out.println(uploadFieldName);
		System.out.println(submitButtonName);

		//File file = new File("/path/to/file/you/want/to/upload.ext");
		InputStream fileContent = new FileInputStream(file);
		String fileContentType = "application/octet-stream"; // Or whatever specific.
		String fileName = file.getAbsolutePath();

		HttpPost httpPost = new HttpPost(url);
		MultipartEntity entity = new MultipartEntity();
		entity.addPart(uploadFieldName, new InputStreamBody(fileContent, fileContentType, fileName));
		//entity.addPart(viewStateName, new StringBody(viewStateValue));
		entity.addPart(submitButtonName, new StringBody(submitButtonValue));
		httpPost.setEntity(entity);
		HttpResponse postResponse = httpClient.execute(httpPost, httpContext);

		String html = EntityUtils.toString(postResponse.getEntity());

		Document document_resultat = Jsoup.parse(html, url);
		System.out.println(document_resultat.html());
	}*/

	/*public void uploadImage(File file) throws ClientProtocolException, IOException {
		String url = "http://saucenao.com/";

		// Based on: http://stackoverflow.com/questions/2017414/post-multipart-request-with-android-sdk

		HttpClient httpclient = HttpClientBuilder.create().build();
		HttpPost post = new HttpPost(url);

		MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
		multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		multipartEntity.setBoundary("---------------------------55712716023497");
		//multipartEntity.addTextBody("name", "file");
		//multipartEntity.addTextBody("filename", file.getName());
		multipartEntity.addPart("file", new FileBody(file));
		multipartEntity.addTextBody("url", "");
		multipartEntity.addTextBody("frame", "1");
		multipartEntity.addTextBody("database", "999");

		post.setEntity(multipartEntity.build());
		HttpResponse response = httpclient.execute(post);
		HttpEntity entity = response.getEntity();

		String html = EntityUtils.toString(entity);
		System.out.println(html);

		System.out.println(response.getStatusLine());  // CONSIDER  Detect server complaints

		entity.consumeContent();
		httpclient.getConnectionManager().shutdown();

	}*/

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		AbstractScrapper p1 = new SauceNaoScrapper("", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0");
		p1.setUrl("http://saucenao.com/search.php?db=999&url=http://home.aidturith.com/private/64f83d06f20c11795e13ce85c277d780_ib4f.jpg");
		try {
			p1.connect();
			p1.buildPage();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		/*AbstractScrapper p1 = new SauceNaoScrapper("", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0");
		File test = new File("D:\\Images\\9528358.jpg");

		try {
			((SauceNaoScrapper) p1).uploadImage(test);
		} catch (IOException e) {
			e.printStackTrace();
		}*/
	}

}
